package cn.seaboot.admin.upload.utils;

import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;

/**
 * 文件请求对象类型转换
 *
 * It can be used in most of the projects, if throw MultipartException{@link org.springframework.web.multipart.MultipartException},
 * you should write MultipartRequestConverter according to your own project.
 *
 * @author Mr.css
 * @version 2020-05-20 15:32
 */
public class DefaultMultipartRequestConverter implements MultipartRequestConverter {
    private final MultipartResolver multipartResolver;

    /**
     * MultipartResolver can get from spring-context, also new a instance
     *
     * @param multipartResolver -
     * @see CommonsMultipartResolver
     * @see org.springframework.web.multipart.support.StandardServletMultipartResolver
     */
    public DefaultMultipartRequestConverter(MultipartResolver multipartResolver) {
        this.multipartResolver = multipartResolver;
    }

    public DefaultMultipartRequestConverter() {
        this.multipartResolver = new CommonsMultipartResolver();
    }

    /**
     * HttpServletRequest to MultipartHttpServletRequest
     *
     * @param request HttpServletRequest
     * @return MultipartHttpServletRequest
     * @throws org.springframework.web.multipart.MultipartException check your request, it can not case to MultipartHttpServletRequest, DefaultMultipartRequestConverter is not fit in your project
     */
    @Override
    public MultipartHttpServletRequest convertToMultipartRequest(HttpServletRequest request) {
        if (request instanceof MultipartHttpServletRequest) {
            return (MultipartHttpServletRequest) request;
        } else {
            if (UploadUtils.isMultipartContent(request)) {
                return multipartResolver.resolveMultipart(request);
            }
            return null;
        }
    }
}
